import { Component, OnInit } from '@angular/core';
import { StorageService } from '../services/storage.service';

/**
 * 创建服务
 * 在APP.MODULE.TS引入并且声明服务 //引入并配置服务
import { StorageService } from './services/storage.service';
 * 具体组件中引入import { StorageService } from '../services/storage.service';
 * 在构造函数中初始化
 * 通过this来获得服务指令 
 */

@Component({
  selector: 'app-todolist',
  templateUrl: './todolist.component.html',
  styleUrls: ['./todolist.component.scss']
})
export class TodolistComponent implements OnInit {

  public keyWord:any;

  public todolist:any[]=[]; // 必须要初始化，否则会报错。

  constructor(public storage:StorageService) {
   }

  ngOnInit() {
      var todolist = this.storage.get('todolist');
      if(todolist){
        this.todolist = todolist;
      }
  }

  onEnter(event) {
    
    console.log(event); 
    if(event.keyCode == 13){
      if(!this.todolistHadKeyWord(this.todolist,this.keyWord)){
        this.todolist.push({
          title:this.keyWord,
          status:0
        });
    
        this.keyWord ='';

        this.storage.set('todolist',this.todolist);
      }else{
        alert("数据已经存在");
        this.keyWord ='';
      }
     
    }
   
  }

  doDelete(key){
    this.todolist.splice(key,1);
      //放入缓存中
      this.storage.set('searchlist',this.todolist);
  }

  todolistHadKeyWord(todolist:any,keyWord:any){
    // foreach会存在异步
    // todolist.forEach(value => {
    //     if(value.title == keyWord){
    //       return true;
    //     }
    // });

    for(var i = 0;i<todolist.length;i++){
      if(todolist[i].title == keyWord){
        return true;
      }
    }
    return false;
  }

  checkboxChange(){
    console.log("进入改变的方法");
     //放入缓存中
     this.storage.set('searchlist',this.todolist);
  }
}
